import { CallbackResult } from '../types/index'

/**
 * 封装轻提示
 */
export const toast = (txt : string | CallbackResult | UniApp.ShowToastOptions, param ?: CallbackResult | UniApp.ShowToastOptions) => {
	const defaultConfig : UniApp.ShowToastOptions = {
		title: '请求成功',
		icon: 'none',
		mask: true,
		duration: 2000,
		position: 'bottom'
	}
	if (txt && typeof txt == 'string') defaultConfig.title = txt
	if (param && typeof param == 'object') Object.assign(defaultConfig, param)
	if (param && typeof param == 'function') defaultConfig.complete = param
	uni.showToast(defaultConfig)
}

/**  
 * 将数字格式化为带有单位的字符串（如千、万、亿、兆）
 * @param num 要格式化的数字
 * @param decimalPlaces 保留的小数位数，默认为2
 * @returns 格式化后的数字和对应的单位，如"1.23万"或"Invalid number"（如果输入无效）
 */
export const formatNumberWithUnit = (num : number, decimalPlaces : number = 2) => {
	if (typeof num !== 'number' || isNaN(num) || !isFinite(num)) {
		return 'Invalid number'
	}

	const units = ['', '万', '亿', '兆']

	let index = 0
	let numStr = num.toString()
	let decimalPointIndex = numStr.indexOf('.')

	if (decimalPointIndex !== -1) {
		numStr = numStr.substring(0, decimalPointIndex + 1 + decimalPlaces)

		if (numStr.slice(decimalPointIndex + 1) === '0'.repeat(decimalPlaces)) {
			numStr = numStr.slice(0, decimalPointIndex)
		}
	}

	while (Math.abs(parseFloat(numStr)) >= 10000 && index < units.length - 1) {
		numStr = numStr.replace(/,/g, '')

		const parts = numStr.split('.')
		const integerPart = parseInt(parts[0], 10) / 10000
		let fractionalPart = ''

		if (parts.length > 1) {
			fractionalPart = parts[1].slice(0, decimalPlaces)
			if (fractionalPart.length < decimalPlaces) {
				fractionalPart += '0'.repeat(decimalPlaces - fractionalPart.length)
			}
		}

		numStr = (integerPart + '.' + fractionalPart).replace(/\.0+$/, '')
		index++;
	}

	return numStr + units[index]
}

/**  
 * 将对象的指定属性从字符串转换为数字（如果可能）
 * 如果不指定propNameOrNames，则默认转换对象的所有字符串属性
 *  
 * @param obj 要处理的对象
 * @param propNameOrNames 要转换的属性名或属性名数组（可选）
 * @returns 转换后的对象
 */
export const convertStringsToNumbers = (obj : Record<string, any>, propNameOrNames ?: string | string[]) : Record<string, any> => {
	if (typeof obj !== 'object' || obj === null) {
		throw new Error('Invalid arguments. First argument must be an object.')
	}

	const propNames = propNameOrNames ? (Array.isArray(propNameOrNames) ? propNameOrNames : [propNameOrNames]) : Object.keys(obj)

	for (const propName of propNames) {
		if (obj.hasOwnProperty(propName) && typeof obj[propName] === 'string') {
			const parsedValue = Number(obj[propName])
			if (!isNaN(parsedValue) && isFinite(parsedValue)) {
				obj[propName] = parsedValue
			}
		}
	}

	return obj
}